const config = require('../../../config/config.js');
const uploadApi = require('../../../api/uploadApi.js');
const regeneratorRuntime = require('../../../module/runtime.js')
const {
  filePrefix
} = config.server;
Component({
  //该主键为表单组件
  behaviors: ['wx://form-field'],
  //定义外部class名字
  externalClasses: ['item-class', 'box-class', 'row-class', 'icon-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    initvalue: { // 初始值
      type: String,
      optionalTypes: [Array],
      value: ""
    },
    max: { // 最大张数
      type: Number,
      value: 1
    },
    source: { // 来源 1 相册，2相机，-1，所有
      type: Number,
      value: -1
    },
    del: { // 是否显示删除按钮
      type: Boolean,
      value: true
    },
    icon: { // 自定义上传icon
      type: String,
      value: null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    icondef: "",
    delicon: "",
    value: [],
    temps: [],
    paths: []
  },
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行

    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  observers: {
    //监听配置文件
    'initvalue': function(value) {
      console.log("触发了==", value);
      let that = this;

      let paths = [];
      if (value) {
        if (Object.prototype.toString.call(value) == '[object Array]') {
          paths = value;
        } else {
          value = String(value);
          if (value != "") {
            paths = value.split(",");
          }
        }
      }
      let setvalue = paths;
      for (var i = 0; i < paths.length; i++) {
        paths[i] = that.fttpath(paths[i]);
      }

      this.setData({
        paths,
        value: setvalue || []
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    fttpath(path) {
      path = path || "";
      if (path.indexOf("http") > -1) {
        return path;
      }
      return filePrefix + path;
    },
    chooseImage: function() {
      let that = this;
      //计算可选张数
      let {
        max,
        source,
        temps,
        paths
      } = that.data;
      let count = max - paths.length - temps.length;
      let sourceType = ['album', 'camera'];
      if (source == 1) {
        sourceType = ['album'];
      } else if (source == 2) {
        sourceType = ['camera'];
      }
      wx.chooseImage({
        count: count,
        sizeType: ['original', 'compressed'],
        sourceType: sourceType,
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          // temps = temps.concat(tempFilePaths);
          // that.setData({
          //   temps
          // })
          //开始上传
          that.uploadFiles(tempFilePaths);
        }
      })
    },
    async uploadFiles(array) {
      let that = this;
      //防止深克隆
      let comdata = JSON.parse(JSON.stringify(that.data))
      let {
        temps,
        paths,
        value
      } = comdata;
      value = value || [];
      wx.showLoading({
        title: '上传中',
        mask: true
      })
      console.log("上传前", {
        temps,
        paths,
        value
      })
      for (var i = 0; i < array.length; i++) {
        let rs = await uploadApi.uploadPic(array[i]);
        console.log("图片上传结果", rs);
        if (rs.path != null) {
          paths.push(that.fttpath(rs.path));
          value.push(rs.path);
          //向父组件传值
          that.bindchange({
            value
          });
        }
      }
      console.log("上传后", {
        temps,
        paths,
        value
      })
      that.setData({
        // temps: [],
        paths,
        value
      })
      wx.hideLoading();
    },
    /**
     * 删除图片
     */
    delImg: function(e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      let thatdata = JSON.parse(JSON.stringify(that.data));
      let {
        value,
        paths
      } = thatdata;
      //移除元素
      value.splice(index, 1);
      paths.splice(index, 1);
      that.setData({
        paths,
        value
      })
      //向父组件传值
      that.bindchange({
        value
      });
    },
    /**
     * 放大图片
     */
    previewImage: function(e) {
      let index = e.currentTarget.dataset.index;
      let urls = this.data.paths;
      wx.previewImage({
        current: index,
        urls: urls
      })
    },
    /**
     * 向外部提供change回调
     */
    bindchange: function(object) {
      this.triggerEvent('change', object);
    }
  }
})